package com.hyhy.hycloud.uaa.controller;

import com.hyhy.hycloud.commons.dto.InvokeResult;
import com.hyhy.hycloud.uaa.Constants;
import com.hyhy.hycloud.uaa.UaaErrorType;
import com.hyhy.hycloud.uaa.client.*;
import com.hyhy.hycloud.uaa.dto.UpdateLoginPassword;
import com.hyhy.hycloud.uaa.model.User;
import com.hyhy.hycloud.uaa.repository.UserRepository;
import com.hyhy.hycloud.uaa.security.exception.UserNotFoundException;
import com.hyhy.hycloud.uaa.service.RequestSignatureService;
import com.hyhy.hycloud.uaa.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;

/**
 * 登录账号REST API
 *
 * @author Xuegui Yuan
 * @date 2018-11-28
 */
@RequestMapping("/login-account")
@RestController
public class LoginAccountController {

    @Autowired
    RequestSignatureService requestSignatureService;

    @Autowired
    UserService userService;

    @Autowired
    UserRepository userRepository;

    @PostMapping("/check/{loginName}")
    public InvokeResult<?> checkLoginAccount(@PathVariable(name = "loginName") String loginName) {
        if (userRepository.existsByUsernameOrMobile(loginName, loginName)) {
            return InvokeResult.success();
        }
        return InvokeResult.error(UaaErrorType.USER_NOT_FOUND.toRuntimeException());
    }

    @PostMapping("/password/update")
    public InvokeResult<Void> updateLoginPassword(@CurrentUserInfo(required = false) UserIdentity userIdentity,
                                                  @RequestBody @Validated UpdateLoginPassword updateLoginPassword)
            throws UnsupportedEncodingException {
        User user;
        // 登录用户使用旧密码修改密码
        if (userIdentity != null && updateLoginPassword.getUpdateType() == 0) {
            userService.updateLoginPassword(userIdentity.getId(), updateLoginPassword.getOldPassword(),
                    updateLoginPassword.getNewPassword());
        } else {
            // 未登录用户修改密码，校验签名
            requestSignatureService.checkSignature(Constants.UPDATE_LOGIN_PASSWORD_BIZ_CODE,
                    updateLoginPassword.getRequestId(),
                    updateLoginPassword.getSignature());
            if (StringUtils.isNoneBlank(updateLoginPassword.getUserId())) {
                user = userRepository.findById(updateLoginPassword.getUserId())
                        .orElseThrow(() -> new UserNotFoundException(UaaErrorType.USER_NOT_FOUND.getMessage()));
            } else if (StringUtils.isNoneBlank(updateLoginPassword.getUsername())) {
                user = userRepository.findByUsername(updateLoginPassword.getUsername())
                        .orElseThrow(() -> new UserNotFoundException(UaaErrorType.USER_NOT_FOUND.getMessage()));
            } else if (StringUtils.isNoneBlank(updateLoginPassword.getMobile())) {
                user = userRepository.findByMobile(updateLoginPassword.getMobile())
                        .orElseThrow(() -> new UserNotFoundException(UaaErrorType.USER_NOT_FOUND.getMessage()));
            }  else {
                throw new IllegalArgumentException("userId or mobile or email must be not blank");
            }
            userService.updateLoginPassword(user, updateLoginPassword.getNewPassword());
        }
        return InvokeResult.success();
    }

    @GetMapping("/test1")
    public InvokeResult<?> testUserInfo3(@CurrentUserInfo UserInfo userInfo,
                                         @RequestParam(name = "timeout", required = false) long timeout) throws InterruptedException {
        Thread.sleep(timeout);
        return InvokeResult.success(userInfo);
    }
}
